<?php

require_once 'dbutils.php';
require_once 'RestUtils.php';
require_once 'Base.php';

class Users extends Base
{

    function GET($matches)
    {
        $req = RestUtils::processRequest('GET');
        $req_vars = $req->getRequestVars();
        $db_vars = dbutils::translate_rest_params($req_vars);
        $res = $this->selectUsers($db_vars);
        if ($res['code'] == 0)
            RestUtils::sendResponse(200, $res['result'], 'application/json');
        else
            RestUtils::sendResponse(404, dbutils::error_to_json($res['code'], $res['message']), 'application/json');
    }

    function POST($matches)
    {
        $req = RestUtils::processRequest('POST');
        $req_vars = $req->getRequestVars();
        $db_vars = dbutils::translate_rest_params($req_vars);
        $res = $this->insertUser($db_vars);
        if ($res['code'] == 0)
            RestUtils::sendResponse(201, $res['result'], 'application/json');
        else
            RestUtils::sendResponse(404, dbutils::error_to_json($res['code'], $res['message']), 'application/json');
    }

    function PUT($matches)
    {
        $req = RestUtils::processRequest('PUT');
        $req_vars = $req->getRequestVars();
        $db_vars = dbutils::translate_rest_params($req_vars);
        $res = $this->updateUser($db_vars);
        if ($res['code'] == 0)
            RestUtils::sendResponse(200);
        else
            RestUtils::sendResponse(404, dbutils::error_to_json($res['code'], $res['message']), 'application/json');
    }

    function DELETE($matches)
    {
        $req = RestUtils::processRequest('DELETE');
        $req_vars = $req->getRequestVars();
        $db_vars = dbutils::translate_rest_params($req_vars);
        $res = $this->deleteUser($db_vars);
        if ($res['code'] == 0)
            RestUtils::sendResponse(200);
        else
            RestUtils::sendResponse(404, dbutils::error_to_json($res['code'], $res['message']), 'application/json');
    }

    private function selectUsers($values)
    {
        $code = 0;
        $msg = '';
        $result = null;
        try {
            if (!$values)
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            if (!array_key_exists('id_user', $values))
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            $db_handle = @pg_pconnect(dbutils::$conn_string);

            $query = "SELECT username,
                             openid,
                             gender,
                             nationality,
                             birth_year,
                             photo,
                             fl_on_line
                      FROM users
                      WHERE id = {$values['id_user']}";

            $result = @pg_query($db_handle, $query);
            if ($result) {
                $userDet = dbutils::dbresult_to_array($result);

                if (@pg_num_rows($result) > 0) {
                    $query = "SELECT ut.cd_tongue,
                                     t.ds_tongue,
                                     ut.priority
                              FROM user_tongues ut, tongues t
                              WHERE ut.id_user = {$values['id_user']}
                              AND ut.cd_tongue = t.cd_tongue";

                    $result = @pg_query($db_handle, $query);
                    if ($result) {
                        $spokenLang = dbutils::dbresult_to_array($result);
                        $userDet[0]['spokenTongues'] = $spokenLang;
                    } else
                        $userDet[0]['spokenTongues'] = array();

                    $query = "SELECT c.cd_contact,
                                     c.ds_contact,
                                     c.priority
                              FROM contacts c
                              WHERE c.id_user = {$values['id_user']}";

                    $result = @pg_query($db_handle, $query);
                    if ($result) {
                        $contacts = dbutils::dbresult_to_array($result);
                        $userDet[0]['contacts'] = $contacts;
                    } else
                        $userDet[0]['contacts'] = array();
                }

                $result = json_encode(dbutils::translate_db_params($userDet));
            } else {
                $code = -1;
                $msg = 'no db records found ' . @pg_last_error($db_handle);
            }
            @pg_close($db_handle);
        } catch (Exception $e) {
            $code = $e->getCode();
            $msg = $e->getMessage();
        }
        return array('code' => $code, 'message' => $msg, 'result' => $result);
    }

    private function insertUser($values)
    {
        $code = 0;
        $msg = '';
        $result = null;
        try {
            if (!$values)
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            if (!array_key_exists('username', $values)
                || !array_key_exists('openid', $values)
                || !array_key_exists('gender', $values)
                || !array_key_exists('nationality', $values)
                || !array_key_exists('birth_year', $values)
            )
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            $db_handle = @pg_pconnect(dbutils::$conn_string);

            $res = @pg_query($db_handle, "SELECT nextval('users_id_seq') as key");
            if ($res) {
                $row = @pg_fetch_array($res, 0);
                $id_user = $row['key'];
            }

            if ($id_user) {
                $photo = '';
                if (array_key_exists('photo', $values))
                    $photo = $values['photo'];

                $insert = "INSERT INTO users (id,
                                            username,
                                            openid,
                                            gender,
                                            nationality,
                                            birth_year,
                                            photo,
                                            fl_on_line)
                                    VALUES ({$id_user},
                                           '{$values['username']}',
                                           '{$values['openid']}',
                                           '{$values['gender']}',
                                           '{$values['nationality']}',
                                           '{$values['birth_year']}',
                                           '{$photo}',
                                           '1');";

                if (array_key_exists('contacts', $values)) {
                    $contacts = $values['contacts'];
                    if ($contacts)
                    foreach ($contacts as $val) {
                        if (!array_key_exists('cd_contact', $val)
                            || !array_key_exists('ds_contact', $val)
                            || !array_key_exists('priority', $val)
                        )
                            return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

                        $insert .= " INSERT INTO contacts (id_user,
                                             cd_contact,
                                             ds_contact,
                                             priority)
                                     VALUES ({$id_user},
                                             '{$val['cd_contact']}',
                                             '{$val['ds_contact']}',
                                             {$val['priority']});";
                    }
                }
                if (array_key_exists('spokenTongues', $values)) {
                    $tongues = $values['spokenTongues'];
                    if ($tongues)
                    foreach ($tongues as $val) {
                        if (!array_key_exists('cd_tongue', $val)
                            || !array_key_exists('priority', $val)
                        )
                            return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

                        $insert .= " INSERT INTO user_tongues (id_user,
                                             cd_tongue,
                                             priority)
                                     VALUES ({$id_user},
                                             '{$val['cd_tongue']}',
                                             {$val['priority']});";
                    }
                }

                $result = @pg_query($db_handle, $insert);
                if ($result)
                    $result = json_encode(array('idUser' => $id_user));
                else {
                    $code = -1;
                    $msg = 'inserting records not possible ' . @pg_last_error($db_handle);
                }
            } else {
                $code = -1;
                $msg = 'error generating idUser ' . @pg_last_error($db_handle);
            }

            @pg_close($db_handle);

        } catch (Exception $e) {
            $code = $e->getCode();
            $msg = $e->getMessage();
        }
        return array('code' => $code, 'message' => $msg, 'result' => $result);
    }


    private function updateUser($values)
    {
        $code = 0;
        $msg = '';
        $result = null;
        try {
            if (!$values)
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            if (!array_key_exists('id_user', $values)
                || !array_key_exists('username', $values)
                || !array_key_exists('gender', $values)
                || !array_key_exists('nationality', $values)
                || !array_key_exists('birth_year', $values)
                || !array_key_exists('fl_on_line', $values)
            )
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            $db_handle = @pg_pconnect(dbutils::$conn_string);

            $update = "UPDATE users
                                SET   username='{$values['username']}',
                                      gender='{$values['gender']}',
                                      nationality='{$values['nationality']}',
                                      birth_year='{$values['birth_year']}',
                                      fl_on_line='{$values['fl_on_line']}'
                                WHERE id={$values['id_user']};";

            if (array_key_exists('photo', $values)) {
                $update .= "UPDATE users
                                SET   photo='{$values['photo']}'
                                WHERE id={$values['id_user']};";
            }

            if (array_key_exists('contacts', $values)) {
                $update .= "DELETE FROM contacts
                                    WHERE id_user={$values['id_user']};";
                $contacts = $values['contacts'];
                if ($contacts)
                foreach ($contacts as $val) {
                    if (!array_key_exists('cd_contact', $val)
                        || !array_key_exists('ds_contact', $val)
                        || !array_key_exists('priority', $val)
                    )
                        return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

                    $update .= " INSERT INTO contacts (id_user,
                                             cd_contact,
                                             ds_contact,
                                             priority)
                                     VALUES ({$values['id_user']},
                                             '{$val['cd_contact']}',
                                             '{$val['ds_contact']}',
                                             {$val['priority']});";
                }
            }
            if (array_key_exists('spokenTongues', $values)) {
                $update .= "DELETE FROM user_tongues
                                    WHERE id_user={$values['id_user']};";
                $tongues = $values['spokenTongues'];
                if ($tongues)
                foreach ($tongues as $val) {
                    if (!array_key_exists('cd_tongue', $val)
                        || !array_key_exists('priority', $val)
                    )
                        return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

                    $update .= " INSERT INTO user_tongues (id_user,
                                             cd_tongue,
                                             priority)
                                     VALUES ({$values['id_user']},
                                             '{$val['cd_tongue']}',
                                             {$val['priority']});";
                }
            }

            $result = @pg_query($db_handle, $update);
            if (!$result) {
                $code = -1;
                $msg = 'updating records not possible ' . @pg_last_error($db_handle);
            }

            @pg_close($db_handle);

        } catch (Exception $e) {
            $code = $e->getCode();
            $msg = $e->getMessage();
        }
        return array('code' => $code, 'message' => $msg, 'result' => $result);
    }


    private function deleteUser($values)
    {
        $code = 0;
        $msg = '';
        $result = null;
        try {
            if (!$values)
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            if (!array_key_exists('id_user', $values))
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            $delete = "DELETE FROM contacts
                                    WHERE id_user={$values['id_user']};";
            $delete .= "DELETE FROM user_tongues
                                    WHERE id_user={$values['id_user']};";
            $delete .= "DELETE FROM users
                                    WHERE id={$values['id_user']};";

            $db_handle = @pg_pconnect(dbutils::$conn_string);

            $result = @pg_query($db_handle, $delete);
            if (!$result) {
                $code = -1;
                $msg = 'deleting records not possible ' . @pg_last_error($db_handle);
            }
            @pg_close($db_handle);
        } catch (Exception $e) {
            $code = $e->getCode();
            $msg = $e->getMessage();
        }
        return array('code' => $code, 'message' => $msg, 'result' => $result);
    }
}

?>
